﻿#include "WRWorkTcpCommClientAffair.h"
#include "WRWorkTcpCommClientInterface.h"
#include "WRWorkTcpCommClientInterfaceActivator.h"
#include "../WRWorkTcpComm.h"
#include "../WRWorkTcpCommConsts.h"

//初始化工作TCP通讯客户端事务。
WRWorkTcpCommClientAffair::WRWorkTcpCommClientAffair(int id, int index, WRWorkTcpCommClientObject* object)
    : WRWorkAffair(object), m_id(id), m_index(index), m_interfaces(256), m_timeout(WRWorkTcpComm::DefaultTimeount), m_sequence(0), m_procEntry(0)
{
    for(WRu i = 0, l = m_interfaces.count(); i < l; ++i)
    {
        m_interfaces[i] = 0;
    }
}
//清理当前对象所占用的相关资源。
WRWorkTcpCommClientAffair::~WRWorkTcpCommClientAffair(void)
{
    WRWorkTcpCommClientObject* owner = object();
    WRWorkTcpCommClientSession* session = owner->session();

    if (session->effective())
    {
        WRDataPacket* packet = WRDataPacket::allocate<32>();
        {
            char* p;
            packet->buffer(&p);

            WRBytes::write((WR32u)WRWorkTcpComm::FrameHeader, p);//帧头
            WRBytes::write((WR32s)(32), p + 4);//帧长度
            WRBytes::write((WR16u)(owner->index()), p + 8);//工作对象索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkObjectAffair, p + 10);//类型（工作事务）
            WRBytes::write((WR32s)(m_id), p + 12);
            WRBytes::write((WR16u)(m_index), p + 16);//工作事务索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkAffairDispose, p + 18);//类型（工作销毁）
            WRBytes::write((WR32u)WRWorkTcpComm::FrameVersion, p + 24);//版本
            WRBytes::write((WR32u)WRWorkTcpComm::FrameTailor, p + 28);//帧尾
        }
        if (!session->sendData(packet))
        {
            packet->release();
        }
    }

    for(WRu i = 0, l = m_interfaces.count(); i < l; ++i)
    {
        Interface interface = m_interfaces[i];
        if (interface)
        {
            delete interface;
        }
    }
    owner->m_affairs[m_index] = 0;
}

//处理数据。
void WRWorkTcpCommClientAffair::procData(const unsigned char* buf, int len)
{
    WR16u cmdType = WRBytes::read<WR16u>(buf);
    buf += 2;
    len -= 2;
    switch (cmdType)
    {
    case WRWorkTcpComm::WorkAffairIIQuery://接口查询
    {
        WR32s serial = WRBytes::read<WR32s>(buf);
        buf += 4;
        len -= 4;

        m_procMutex.lock();
        if (m_procEntry && m_procEntry->serial() == serial)
        {
            Interface interface = 0;
            WR32s result = WRBytes::read<WR16s>(buf);
            if (result >= 0)
            {
                WRWorkTcpCommClientInterfaceActivator* activator = WRWorkTcpComm::selectClientInterface(m_procEntry->uuid());
                if (activator)
                {
                    interface = activator->create(result, this);
                    m_interfaces[result] = interface;
                }
            }
            m_procEntry->fulfil(interface);
        }
        m_procMutex.unlock();
    }
        break;
    case WRWorkTcpComm::WorkAffairIITreat://接口处理
    {
        WR16u index = WRBytes::read<WR16u>(buf);
        buf += 2;
        len -= 2;

        Interface interface = m_interfaces[index];
        if (interface)
        {
            interface->procData(buf, len);
        }
    }
        break;
    default:
        break;
    }
}

//查询指定标识的工作处理者。
WRWorkDealer* WRWorkTcpCommClientAffair::queryWorkDealer(const QUuid &uuid)
{
    QMutexLocker lck(&m_mutex);

    for(WRu i = 0, l = m_interfaces.count(); i < l; ++i)
    {
        Interface interface = m_interfaces[i];
        if (interface && interface->uuid() == uuid)
        {
            return interface->workDealer();
        }
    }

    WRWorkTcpCommClientObject* owner = object();
    WRWorkTcpCommClientSession* session = owner->session();
    if (session->effective())
    {
        ++m_sequence;

        WRDataPacket* packet = WRDataPacket::allocate<56>();
        {
            char* p;
            packet->buffer(&p);

            WRBytes::write((WR32u)WRWorkTcpComm::FrameHeader, p);//帧头
            WRBytes::write((WR32s)(56), p + 4);//帧长度
            WRBytes::write((WR16u)(owner->index()), p + 8);//工作对象索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkObjectAffair, p + 10);//类型（工作事务）
            WRBytes::write((WR32s)(m_id), p + 12);
            WRBytes::write((WR16u)(m_index), p + 16);//工作事务索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkAffairIIQuery, p + 18);//类型（接口查询）
            WRBytes::write((WR32s)(m_sequence), p + 20);//指令序号
            WRBytes::write((WR16u)WRWorkTcpComm::WorkDealer, p + 24);//接口标识
            WRBytes::write((QUuid)(uuid), p + 32);//接口标识
            WRBytes::write((WR32u)WRWorkTcpComm::FrameVersion, p + 48);//版本
            WRBytes::write((WR32u)WRWorkTcpComm::FrameTailor, p + 52);//帧尾
        }

        m_procMutex.lock();
        if (session->sendData(packet))
        {
            m_procEntry = new ProcEntry(uuid, m_sequence);
        }
        else
        {
            packet->release();
        }
        m_procMutex.unlock();
    }

    if (m_procEntry)
    {
        m_procEntry->wait(m_timeout);

        Interface interface = 0;
        m_procMutex.lock();
        {
            interface = m_procEntry->target();
            delete m_procEntry;
            m_procEntry = 0;
        }
        m_procMutex.unlock();
        if (interface)
        {
            return interface->workDealer();
        }
    }
    return 0;
}
//查询指定标识的任务处理者。
WRTaskDealer* WRWorkTcpCommClientAffair::queryTaskDealer(const QUuid& uuid)
{
    QMutexLocker lck(&m_mutex);

    for(WRu i = 0, l = m_interfaces.count(); i < l; ++i)
    {
        Interface interface = m_interfaces[i];
        if (interface && interface->uuid() == uuid)
        {
            return interface->taskDealer();
        }
    }

    WRWorkTcpCommClientObject* owner = object();
    WRWorkTcpCommClientSession* session = owner->session();
    if (session->effective())
    {
        ++m_sequence;

        WRDataPacket* packet = WRDataPacket::allocate<56>();
        {
            char* p;
            packet->buffer(&p);

            WRBytes::write((WR32u)WRWorkTcpComm::FrameHeader, p);//帧头
            WRBytes::write((WR32s)(56), p + 4);//帧长度
            WRBytes::write((WR16u)(owner->index()), p + 8);//工作对象索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkObjectAffair, p + 10);//类型（工作事务）
            WRBytes::write((WR32s)(m_id), p + 12);
            WRBytes::write((WR16u)(m_index), p + 16);//工作事务索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkAffairIIQuery, p + 18);//类型（接口查询）
            WRBytes::write((WR32s)(m_sequence), p + 20);//指令序号
            WRBytes::write((WR16u)WRWorkTcpComm::TaskDealer, p + 24);//接口标识
            WRBytes::write((QUuid)(uuid), p + 32);//接口标识
            WRBytes::write((WR32u)WRWorkTcpComm::FrameVersion, p + 48);//版本
            WRBytes::write((WR32u)WRWorkTcpComm::FrameTailor, p + 52);//帧尾
        }

        m_procMutex.lock();
        if (session->sendData(packet))
        {
            m_procEntry = new ProcEntry(uuid, m_sequence);
        }
        else
        {
            packet->release();
        }
        m_procMutex.unlock();
    }

    if (m_procEntry)
    {
        m_procEntry->wait(m_timeout);

        Interface interface = 0;
        m_procMutex.lock();
        {
            interface = m_procEntry->target();
            delete m_procEntry;
            m_procEntry = 0;
        }
        m_procMutex.unlock();
        if (interface)
        {
            return interface->taskDealer();
        }
    }
    return 0;
}
//查询指定标识的数据源接口。
WRDataSource* WRWorkTcpCommClientAffair::queryDataSource(const QUuid& uuid)
{
    QMutexLocker lck(&m_mutex);

    for(WRu i = 0, l = m_interfaces.count(); i < l; ++i)
    {
        Interface interface = m_interfaces[i];
        if (interface && interface->uuid() == uuid)
        {
            return interface->dataSource();
        }
    }

    WRWorkTcpCommClientObject* owner = object();
    WRWorkTcpCommClientSession* session = owner->session();
    if (session->effective())
    {
        ++m_sequence;

        WRDataPacket* packet = WRDataPacket::allocate<56>();
        {
            char* p;
            packet->buffer(&p);

            WRBytes::write((WR32u)WRWorkTcpComm::FrameHeader, p);//帧头
            WRBytes::write((WR32s)(56), p + 4);//帧长度
            WRBytes::write((WR16u)(owner->index()), p + 8);//工作对象索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkObjectAffair, p + 10);//类型（工作事务）
            WRBytes::write((WR32s)(m_id), p + 12);
            WRBytes::write((WR16u)(m_index), p + 16);//工作事务索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkAffairIIQuery, p + 18);//类型（接口查询）
            WRBytes::write((WR32s)(m_sequence), p + 20);//指令序号
            WRBytes::write((WR16u)WRWorkTcpComm::DataSource, p + 24);//接口标识
            WRBytes::write((QUuid)(uuid), p + 32);//接口标识
            WRBytes::write((WR32u)WRWorkTcpComm::FrameVersion, p + 48);//版本
            WRBytes::write((WR32u)WRWorkTcpComm::FrameTailor, p + 52);//帧尾
        }

        m_procMutex.lock();
        if (session->sendData(packet))
        {
            m_procEntry = new ProcEntry(uuid, m_sequence);
        }
        else
        {
            packet->release();
        }
        m_procMutex.unlock();
    }

    if (m_procEntry)
    {
        m_procEntry->wait(m_timeout);

        Interface interface = 0;
        m_procMutex.lock();
        {
            interface = m_procEntry->target();
            delete m_procEntry;
            m_procEntry = 0;
        }
        m_procMutex.unlock();
        if (interface)
        {
            return interface->dataSource();
        }
    }
    return 0;
}
//查询指定标识的事件源接口。
WREventSource* WRWorkTcpCommClientAffair::queryEventSource(const QUuid& uuid)
{
    QMutexLocker lck(&m_mutex);

    for(WRu i = 0, l = m_interfaces.count(); i < l; ++i)
    {
        Interface interface = m_interfaces[i];
        if (interface && interface->uuid() == uuid)
        {
            return interface->eventSource();
        }
    }

    WRWorkTcpCommClientObject* owner = object();
    WRWorkTcpCommClientSession* session = owner->session();
    if (session->effective())
    {
        ++m_sequence;

        WRDataPacket* packet = WRDataPacket::allocate<56>();
        {
            char* p;
            packet->buffer(&p);

            WRBytes::write((WR32u)WRWorkTcpComm::FrameHeader, p);//帧头
            WRBytes::write((WR32s)(56), p + 4);//帧长度
            WRBytes::write((WR16u)(owner->index()), p + 8);//工作对象索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkObjectAffair, p + 10);//类型（工作事务）
            WRBytes::write((WR32s)(m_id), p + 12);
            WRBytes::write((WR16u)(m_index), p + 16);//工作事务索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkAffairIIQuery, p + 18);//类型（接口查询）
            WRBytes::write((WR32s)(m_sequence), p + 20);//指令序号
            WRBytes::write((WR16u)WRWorkTcpComm::EventSource, p + 24);//接口标识
            WRBytes::write((QUuid)(uuid), p + 32);//接口标识
            WRBytes::write((WR32u)WRWorkTcpComm::FrameVersion, p + 48);//版本
            WRBytes::write((WR32u)WRWorkTcpComm::FrameTailor, p + 52);//帧尾
        }

        m_procMutex.lock();
        if (session->sendData(packet))
        {
            m_procEntry = new ProcEntry(uuid, m_sequence);
        }
        else
        {
            packet->release();
        }
        m_procMutex.unlock();
    }

    if (m_procEntry)
    {
        m_procEntry->wait(m_timeout);

        Interface interface = 0;
        m_procMutex.lock();
        {
            interface = m_procEntry->target();
            delete m_procEntry;
            m_procEntry = 0;
        }
        m_procMutex.unlock();
        if (interface)
        {
            return interface->eventSource();
        }
    }
    return 0;
}
//查询指示标识的状态源接口。
WRStateSource* WRWorkTcpCommClientAffair::queryStateSource(const QUuid& uuid)
{
    QMutexLocker lck(&m_mutex);

    for(WRu i = 0, l = m_interfaces.count(); i < l; ++i)
    {
        Interface interface = m_interfaces[i];
        if (interface && interface->uuid() == uuid)
        {
            return interface->stateSource();
        }
    }

    WRWorkTcpCommClientObject* owner = object();
    WRWorkTcpCommClientSession* session = owner->session();
    if (session->effective())
    {
        ++m_sequence;

        WRDataPacket* packet = WRDataPacket::allocate<56>();
        {
            char* p;
            packet->buffer(&p);

            WRBytes::write((WR32u)WRWorkTcpComm::FrameHeader, p);//帧头
            WRBytes::write((WR32s)(56), p + 4);//帧长度
            WRBytes::write((WR16u)(owner->index()), p + 8);//工作对象索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkObjectAffair, p + 10);//类型（工作事务）
            WRBytes::write((WR32s)(m_id), p + 12);
            WRBytes::write((WR16u)(m_index), p + 16);//工作事务索引
            WRBytes::write((WR16u)WRWorkTcpComm::WorkAffairIIQuery, p + 18);//类型（接口查询）
            WRBytes::write((WR32s)(m_sequence), p + 20);//指令序号
            WRBytes::write((WR16u)WRWorkTcpComm::StateSource, p + 24);//接口标识
            WRBytes::write((QUuid)(uuid), p + 32);//接口标识
            WRBytes::write((WR32u)WRWorkTcpComm::FrameVersion, p + 48);//版本
            WRBytes::write((WR32u)WRWorkTcpComm::FrameTailor, p + 52);//帧尾
        }

        m_procMutex.lock();
        if (session->sendData(packet))
        {
            m_procEntry = new ProcEntry(uuid, m_sequence);
        }
        else
        {
            packet->release();
        }
        m_procMutex.unlock();
    }

    if (m_procEntry)
    {
        m_procEntry->wait(m_timeout);

        Interface interface = 0;
        m_procMutex.lock();
        {
            interface = m_procEntry->target();
            delete m_procEntry;
            m_procEntry = 0;
        }
        m_procMutex.unlock();
        if (interface)
        {
            return interface->stateSource();
        }
    }
    return 0;
}
